<?php
//员工
namespace app\crm\model;

use think\Db;
use app\crm\model\Sn;
use app\shop\model\Client as ClientModel;
use app\shop\model\Clientbill as ClientbillModel;
use app\shop\model\ClientCategory as ClientCategoryModel;
use app\shop\model\ClientLog as ClientLogModel;

class Staff extends \ShopModel
{
    protected $table = 'sh_crm_staff';
    protected $pk = 'staff_id';
    public function StaffDb(){
        return Db::name('crm_staff');
    }
    /**
     * 生成密码盐
     */
    public function generateSalt()
    {
        $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
        $strMaxIndex = strlen($str) - 1;
        $salt = '';
        $saltLenght = 6;
        for ($i = 0; $i < $saltLenght; $i ++) {
            $salt.= $str[mt_rand(0, $strMaxIndex)];
        }
        return $salt;
    }

    public function getCustodianTrans($status){
        $all_status = array(
            0 => '否',
            1 => '是',
        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }
    public function getLoginTrans($source){
        $all_status = array(
            0 => '不允许',
            1 => '允许',
         );
        return !empty($all_status[$source]) ? $all_status[$source] : '未知';
    }
    public function search($params){
        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 10;
        $where = [];
        $params['is_sublevel'] = $params['is_sublevel'] == 'true' ? 1 : 0;
        if($params['is_sublevel']){
           $Department = new \app\crm\controller\Department();
           $department_id_arr =  $Department->getDepartmentAffiliate($params['department_id'],1);
            $where['staff.department_id'] =  ['in',$department_id_arr];
        }else{
            $where['staff.department_id'] = $params['department_id'];
        }

        if(!empty($params['query'])){
            $where['staff.staff_name | staff.phone | staff.qq | staff.email '] = ['like','%'.$params['query'].'%'];
        }
        if($params['sys_custodian']!=2){
            $where['staff.sys_custodian'] = $params['sys_custodian'];
        }
        if($params['is_login']!=2){
            $where['staff.is_login'] = $params['is_login'];
        }
        if($params['login_lock']!=2){
            $where['staff.login_lock'] = $params['login_lock'];
        }
        if($params['attention_type']!=2){
            $where['staff.attention_type'] = $params['attention_type'];
        }
        if($params['dimission_type']!=2){
            $where['staff.dimission_type'] = $params['dimission_type'];
        }
        $where['staff.is_downstream'] = 1;
        //排除上下游互动
        $Sys = new Sys();
        $did = $Sys->where('id',1)->value('crm_sxyhd_did');
       // $where['staff.department_id']=['neq',$did];

        $data = $this->alias('staff')
            ->join('sh_crm_department department','staff.department_id = department.department_id')
            ->field('staff.staff_id,staff.staff_name,staff.head_img, department.department_name,staff.phone, staff.entry_time, staff.sys_custodian, staff.is_login, staff.attention_type')
            ->where($where)
            ->where('staff.department_id','neq',$did)
            ->page($page,$pageSize)
            ->order('staff.staff_id desc')
            ->select();

        foreach($data as &$v){
            $v['sys_custodian'] = $this->getCustodianTrans($v['sys_custodian']);
            $v['is_login'] = $this->getLoginTrans($v['is_login']);
            $v['entry_time'] = date('Y-m-d',$v['entry_time']);

        }

        //获取分页数据
        $count = $this->alias('staff')
            ->join('sh_crm_department department','staff.department_id = department.department_id')
            ->field('staff.staff_id,staff.staff_name,staff.head_img, department.department_name,staff.phone, staff.entry_time, staff.sys_custodian, staff.login_lock, staff.attention_type')
            ->where($where)
            ->where('staff.department_id','neq',$did)
            ->order('staff.staff_id desc')
            ->count();

        $pager = [
            'total' => $count,
            'page' => $page,
            'pageSize' => $pageSize
        ];



        return [
            'staff' => $data,
            'pager' => $pager
        ];

    }

    //简单筛选
    public function easySearch($params){
        $where = [];
        if(!empty($params['query'])){
            $where['staff.staff_name | staff.phone | staff.qq | staff.email '] = ['like','%'.$params['query'].'%'];
        }
        $where['staff.is_downstream'] = 1;
        $data = $this->alias('staff')
            ->join('sh_crm_department department','staff.department_id = department.department_id')
            ->field('staff.staff_id,staff.staff_name,staff.head_img,department.department_name')
            ->where($where)
            ->order('staff.staff_id desc')
            ->select();
        foreach($data as &$v){
            $v['is_checked'] = false;
        };
        return $data;
    }
     //简单筛选
    public function easySearchDown($params){
        $where = [];
        if(!empty($params['query'])){
            $where['staff.staff_name | staff.phone | staff.qq | staff.email '] = ['like','%'.$params['query'].'%'];
        }
        $where['staff.is_downstream'] = 0;
        $data = $this->alias('staff')
            
            ->field('staff.staff_id,staff.staff_name,staff.head_img')
            ->where($where)
            ->order('staff.staff_id desc')
            ->select();
        foreach($data as &$v){
           
            $v['is_checked'] = false;
        };
        return $data;
    }
    //简单筛选2参数2人员范围
    public function easySearch2($params,$stafflist){
        $where = [];
        if(!empty($params['query'])){
            $where['staff.staff_name | staff.phone | staff.qq | staff.email '] = ['like','%'.$params['query'].'%'];
        }
        if($stafflist){
            $where2="staff.staff_id in ($stafflist)";
        }else{
            $where2="1=2";
        }
        $where['staff.is_downstream'] = 1;
        $data = $this->alias('staff')
            ->join('sh_crm_department department','staff.department_id = department.department_id')
            ->field('staff.staff_id,staff.staff_name,staff.head_img,department.department_name')
            ->where($where)->where($where2)
            ->order('staff.staff_id desc')
            ->select();
        foreach($data as &$v){
            $v['is_checked'] = false;
        };
        return $data;
    }
    //简单筛选3拥有使用crm权限
    public function easySearch3($params,$ids){
        $where = [];
        if(!empty($params['query'])){
            $where['staff.staff_name | staff.phone | staff.qq | staff.email '] = ['like','%'.$params['query'].'%'];
        }
        $where['staff.is_downstream'] = 1;
        $data = $this->alias('staff')
            ->join('sh_crm_department department','staff.department_id = department.department_id')
            ->field('staff.staff_id,staff.staff_name,staff.head_img,department.department_name')
            ->where($where)->where("staff.staff_id in ($ids)")
            ->order('staff.staff_id desc')
            ->select();
        foreach($data as &$v){
            $v['is_checked'] = false;
        };
        return $data;
    }

    //导入联系人
    public function importStaff($data){
        
        $utid = \request()->header('userId');
        $utname = Db::name('crm_staff')->where('staff_id',$utid)->value('staff_name');

        $error = [];

        foreach($data as &$v){

            //验证
            if(empty($v['staff_name'])){
                $error[] = '第'.($k+1).'行联系人名称不能为空';
                continue;
            }

            if(empty($v['phone'])){
                $error[] = '第'.($k+1).'行联系人手机号不能为空';
                continue;
            }

            //联系人手机号
            $flag = Db::name('crm_staff')->where('phone',$v['phone'])->value('staff_id');
            if($flag){
                $error[] = '第'.($k+1).'行联系人手机号已存在';
                continue;
            }

            //性别
            if($v['sex'] === '男'){
                $v['sex'] = 1;
            }else{
                $v['sex'] = 0;
            }
            

            $create_staff = $utname;
            $datetime = date('Y-m-d H:i:s');

            $SN  = new Sn();
            $snS = $SN->getSn('YG');

            $v['create_at'] = $datetime;
            $v['update_at'] = $datetime;
            $v['last_contract_time'] = $datetime;

            $v['create_staff'] = $create_staff;
            $v['update_staff'] = $create_staff;
            $v['last_contract_staff'] = $create_staff;

            $v['staff_id'] = $snS['0'];

            $this->data($v)->allowField(true)->isUpdate(false)->save();

            $staff_id = $this->staff_id;

            $crm_index = new \app\crmindex\controller\Staff();
            $crm_index->addxy($staff_id,$params['staff_name'],$params['phone'],$params['duty']);

            //联系人标签
            if(!empty($v['tag'])){
                $tag_arr = explode(',',$v['tag']);
                foreach($tag_arr as $tag){
                    $tag_id = Db::name('tag')->where('tag_name',$tag)->value('tag_id');
                    if(!$tag_id){
                        $tag_data = [
                            'tag_name' => $tag
                        ];
                        $tag_id = Db::name('tag')->insertGetId($tag_data);
                    }
                    $staff_tag_relevance = [
                        'staff_id' => $staff_id,
                        'tag_id' => $tag_id
                    ];
                    Db::name('crm_staff_tag_relevance')->insert($staff_tag_relevance);
                }
            }

            //联系人日志
            $staff_log = [
                'staff_id' => $staff_id,
                'operater' => $create_staff,
                'content' => '初始导入',
                'create_at' => $datetime
            ];

            Db::name('crm_staff_log')->insert($staff_log);

            if(!empty($v['client_name'])){
                $client_arr = explode(',',$v['client_name']);
                foreach($client_arr as $client){
                    $client_id = Db::name('client')->where('client_name',$client)->value('client_id');
                    if($client_id){
    
                        //添加关联
                        $client_staff_relevance = [
                            'client_id' => $client_id,
                            'staff_id' => $staff_id
                        ];
                        Db::name('client_staff_relevance')->insert($client_staff_relevance);

                        //客户日志
                        $client_log = [
                            'client_id' => $client_id,
                            'operater' => $create_staff,
                            'content' => '初始导入',
                            'create_at' => $datetime
                        ];

                        Db::name('client_log')->insert($client_log);
                    }
                }
            }

        }

        return $error;

    }

    //获取权限
    public function getAccess($staff_id){
        $has=Db::name("crm_rule_staff")->where(["staff_id"=>$staff_id])->find();
        $c=[];
        if($has){
            $c["hasrole"]=1;
            if($has["is_manager"]==1){
                $c["is_manager"]=1;
                $c["area_list"]=[];
                $c["power"]=[];
            }else{
                $c["is_manager"]=0;
                $area_list=Db::name("crm_rule_area")->where(["staff_id"=>$staff_id])->value("area_list");
                if($area_list){
                    $c["area_list"]=explode(',',$area_list);
                }else{
                    $c["area_list"]=[];
                }
                $poweruser=Db::name("crm_rule_power_user")->where(["staff_id"=>$staff_id])->find();
                if($poweruser){
                    if($poweruser["group_id"]){
                        $power=Db::name("crm_rule_power")->where(["obj_id"=>$poweruser["group_id"],"type"=>2])->field("check_p,add_p,update_p,delete_p,down_p,he_p,re_p,yaoqin_p")->find();
                    }else{
                        $power=Db::name("crm_rule_power")->where(["obj_id"=>$poweruser["staff_id"],"type"=>1])->field("check_p,add_p,update_p,delete_p,down_p,he_p,re_p,yaoqin_p")->find();
                    }
                    if(!$power){
                        $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
                    }
                }else{
                    $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
                }
                $c["power"]=$power;
            }
        }else{
            $c["hasrole"]=0;
        }

        return $c;

    }

}
